package cn.gailvlun.gll.presentation.chat;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.bean.SelectHolder;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.databinding.ActivityReviewCheckInBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.apartment.room.Room;
import cn.gailvlun.gll.net.apartment.room.Task;
import cn.gailvlun.gll.net.apartment.task.TaskRecord;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.adapter.ReviewCheckInTagAdapter;
import cn.gailvlun.gll.presentation.chat.adapter.UnReviewedAdapter;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.FilterView;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.realm.Realm;



public class ReviewCheckInActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {

    public static void openActivity(Context context, int roomId) {
        Intent intent = new Intent(context, ReviewCheckInActivity.class);
        intent.putExtra("roomId", roomId);
        context.startActivity(intent);
    }

    private ActivityReviewCheckInBinding mBinding;

    private ReviewCheckInTagAdapter tagAdapter;
    private GridLayoutManager tagLayoutManager;

    private UnReviewedAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_review_check_in);
        mBinding.setPresenter(new Presenter());

        tagAdapter = new ReviewCheckInTagAdapter(mContext);
        tagAdapter.setPresenter(new Presenter());
        mBinding.tagRv.setAdapter(tagAdapter);

        tagLayoutManager = new GridLayoutManager(mContext, 4);
        mBinding.tagRv.setLayoutManager(tagLayoutManager);

        
        mAdapter = new UnReviewedAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.refreshLayout.setOnRefreshListener(this);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });

        mBinding.filterView.setOnToggleListener(new FilterView.OnToggleListener() {
            @Override
            public void onToggle(boolean isOpen, FilterView.Type type) {
                if (isOpen) {
                    
                } else {
                    
                    Task task = tagAdapter.getCurrentTask();

                    if (mBinding.getTask().getSequence_num() == task.getSequence_num()) {
                        
                        return;
                    }

                    mBinding.setTask(task);

                    
                    mBinding.refreshLayout.autoRefresh();
                }
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        int roomId = getIntent().getIntExtra("roomId", -1);
        if (roomId != -1) {
            Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
            Room room = realm.copyFromRealm(realm.where(Room.class)
                    .equalTo("id", roomId)
                    .findFirst());
            realm.close();

            List<Task> tasks = room.getTasks();
            List<SelectHolder<Task>> selectHolders = SelectHolder.transform(tasks);
            
            selectHolders.get(0).setSelected(true);
            mBinding.setTask(selectHolders.get(0).getData());
            tagAdapter.set(selectHolders);

            mBinding.refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        HttpMethods.getTaskService()
                .getTaskRecordList(mBinding.getTask().getId())
                .compose(RxUtil.<ListRes<TaskRecord>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<TaskRecord>>() {
                    @Override
                    protected void onSuccess(ListRes<TaskRecord> response) {
                        if (!IsEmpty.list(response.getResults())) {
                            mAdapter.set(response.getResults());
                        } else {
                            mAdapter.clear();
                        }
                        mBinding.refreshLayout.setEnableLoadmore(response.isNext());
                        mBinding.refreshLayout.finishRefresh();
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<TaskRecord> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                        mBinding.refreshLayout.finishRefresh();
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {

    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onPhoto(View view, TaskRecord item) {
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(mContext,
                            view, mContext.getString(R.string.shared_image));
            PhotoActivity.openActivity(mContext, item.getPic(), options.toBundle());
        }

        public void onToggle() {
            mBinding.filterView.toggle();
        }

        public void onTagSelected(SelectHolder<Task> taskSelectHolder) {
            for (SelectHolder<Task> selectHolder : tagAdapter.getData()) {
                if (selectHolder != taskSelectHolder) {
                    selectHolder.setSelected(false);
                } else {
                    selectHolder.setSelected(true);
                }
            }
            tagAdapter.notifyDataSetChanged();
        }
    }

    public static class Util {

        public static String getCoupleAvatar(TaskRecord item) {
            if (item.getCouple() == null) {
                return null;
            } else {
                return item.getCouple().getOwner().getAvatar();
            }
        }

        public static int getCoupleAvatarVisibility(TaskRecord item) {
            if (item.getCouple() == null) {
                return View.GONE;
            } else {
                return View.VISIBLE;
            }
        }

        public static String getTaskProducerName(TaskRecord item) {
            if (item.getCouple() == null) {
                return item.getMember().getOwner().getName();
            } else {
                return item.getMember().getCpname();
            }
        }
    }
}
